package com.lh.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lh.entity.table.CompanyData;
import com.lh.mapper.CompanyDataMapper;

import com.lh.service.CompanyDataService;
import com.lh.utils.Answer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CompanyDataServiceImpl implements CompanyDataService {

    @Autowired
    private CompanyDataMapper companyDataMapper;


    @Override
    public Answer<Object> addCompanyData(CompanyData companyData) {
        try{
            companyData.setCreatedTime(new Date());
            companyDataMapper.insert(companyData);
            return Answer.ok("添加成功");
        }catch (Exception e){
            e.printStackTrace();
            return Answer.error("添加失败");
        }
    }


    @Override
    public Answer<Object> updateCompanyData(CompanyData companyData) {
        try{
            Integer id = companyData.getId();
            if (id == null){
                return Answer.error("id不能为空");
            }
            companyDataMapper.updateById(companyData);
            return Answer.ok("更新成功");
        }catch (Exception e){
            e.printStackTrace();
            return Answer.error("更新失败");
        }
    }

    @Override
    public Answer<Object> deleteCompanyData(CompanyData companyData) {
        try{
            Integer id = companyData.getId();
            if (id == null){
                return Answer.error("id不能为空");
            }
            companyDataMapper.deleteById(id);
            return Answer.ok("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return Answer.error("删除失败");
        }
    }

    private LocalDate getLatestMonth() {
        // 查询最大的dataMonth（按月份倒序取第一条）
        LambdaQueryWrapper<CompanyData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(CompanyData::getDataMonth)
                .orderByDesc(CompanyData::getDataMonth)
                .last("LIMIT 1"); // 只取最大的那个月份
        CompanyData latestData = companyDataMapper.selectOne(queryWrapper);
        return latestData != null ? latestData.getDataMonth() : null;
    }




    @Override
    public Answer<Object> queryCompanyDataList(CompanyData companyData) {
        try{
            LambdaQueryWrapper<CompanyData> companyDataLambdaQueryWrapper = new LambdaQueryWrapper<>();
            String name = companyData.getName();
            String departmentName = companyData.getDepartmentName();
            String personResponsible = companyData.getPersonResponsible();
            String power = companyData.getPower();
            String invoicing = companyData.getInvoicing();
            String problem = companyData.getProblem();
            if (StrUtil.isNotBlank(name)){
                companyDataLambdaQueryWrapper.eq(CompanyData::getName,name);
            }
            if (StrUtil.isNotBlank(departmentName)){
                companyDataLambdaQueryWrapper.eq(CompanyData::getDepartmentName,departmentName);
            }
            if (StrUtil.isNotBlank(personResponsible)){
                companyDataLambdaQueryWrapper.eq(CompanyData::getPersonResponsible,personResponsible);
            }
            if (StrUtil.isNotBlank(power)){
                companyDataLambdaQueryWrapper.eq(CompanyData::getPower,power);
            }
            if (StrUtil.isNotBlank(invoicing)){
                companyDataLambdaQueryWrapper.eq(CompanyData::getInvoicing,invoicing);
            }
            if (StrUtil.isNotBlank(problem)){
                companyDataLambdaQueryWrapper.like(CompanyData::getProblem,problem);
            }
            // 核心：默认查询最新月份的全部数据
            LocalDate dataMonth = companyData.getDataMonth();
            if (dataMonth == null) {
                // 前端未指定月份，自动筛选最新月份
                LocalDate latestMonth = getLatestMonth();
                if (latestMonth != null) {
                    companyDataLambdaQueryWrapper.eq(CompanyData::getDataMonth, latestMonth);
                } else {
                    // 表中无数据，返回空列表
                    return Answer.ok(Collections.emptyList());
                }
            } else {
                // 前端指定了月份，按指定月份查询
                companyDataLambdaQueryWrapper.eq(CompanyData::getDataMonth, dataMonth);
            }

            companyDataLambdaQueryWrapper.orderByAsc(CompanyData::getId);
            List<CompanyData> list = companyDataMapper.selectList(companyDataLambdaQueryWrapper);
            return Answer.ok(list);
        }catch (Exception e){
            e.printStackTrace();
            return Answer.error("查询失败");
        }
    }

    @Override
    public Answer<Object> queryCompanyDataPage(JSONObject reqJson) {
        try {
            Integer pageSize = reqJson.getInteger("pageSize");
            Integer pageNum = reqJson.getInteger("pageNum");
            Page<CompanyData> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<CompanyData> companyDataLambdaQueryWrapper = new LambdaQueryWrapper<>();
            String name = reqJson.getString("name");
            String departmentName = reqJson.getString("departmentName");
            String personResponsible = reqJson.getString("personResponsible");
            String power = reqJson.getString("power");
            String invoicing = reqJson.getString("invoicing");
            String problem = reqJson.getString("problem");
            String lampStatus = reqJson.getString("lampStatus");
            String business = reqJson.getString("business");

            if (StrUtil.isNotBlank(name)){
                companyDataLambdaQueryWrapper.eq(CompanyData::getName,name);
            }
            if (StrUtil.isNotBlank(departmentName)){
                companyDataLambdaQueryWrapper.eq(CompanyData::getDepartmentName,departmentName);
            }
            if (StrUtil.isNotBlank(personResponsible)){
                companyDataLambdaQueryWrapper.like(CompanyData::getPersonResponsible,personResponsible);
            }
            if (StrUtil.isNotBlank(power)){
                companyDataLambdaQueryWrapper.eq(CompanyData::getPower,power);
            }
            if (StrUtil.isNotBlank(invoicing)){
                companyDataLambdaQueryWrapper.eq(CompanyData::getInvoicing,invoicing);
            }
            if (StrUtil.isNotBlank(problem)){
                companyDataLambdaQueryWrapper.like(CompanyData::getProblem,problem);
            }
            if (StrUtil.isNotBlank(lampStatus)){
                companyDataLambdaQueryWrapper.eq(CompanyData::getLampStatus,lampStatus);
            }
            if (StrUtil.isNotBlank(business)){
                companyDataLambdaQueryWrapper.eq(CompanyData::getBusiness,business);
            }
            // 前端未指定月份，自动筛选最新月份
            LocalDate latestMonth = getLatestMonth();
            if (latestMonth != null) {
                companyDataLambdaQueryWrapper.eq(CompanyData::getDataMonth, latestMonth);
            } else {
                // 表中无数据，返回空列表
                return Answer.ok(Collections.emptyList());
            }
            Page<CompanyData> companyDataPage = companyDataMapper.selectPage(page, companyDataLambdaQueryWrapper);
            List<CompanyData> records = companyDataPage.getRecords();

            List<CompanyData> companyData = companyDataMapper.selectList(new LambdaQueryWrapper<CompanyData>().ne(CompanyData::getDataMonth, latestMonth));

            Map<String, Long> nameToRedCountMap = companyData.stream()
                    .filter(data -> "2".equals(data.getLampStatus()))
                    // 按名称分组，统计每个分组的数量
                    .collect(Collectors.groupingBy(
                            CompanyData::getName,  // 分组键：名称
                            Collectors.counting()  // 分组值：统计数量（long类型）
                    ));

            records.forEach(record -> {
                String recordName = record.getName();
                // 从Map中获取当前名称对应的数量，若不存在则为0
                long redCount = nameToRedCountMap.getOrDefault(recordName, 0L);
                // 赋值给redCount属性（假设redCount为int类型，需强转）
                record.setRedCount((int) redCount);
            });
            companyDataPage.setRecords(records);
            return Answer.ok(companyDataPage);
        }catch (Exception e){
            e.printStackTrace();
            return Answer.error("查询失败");
        }
    }



    // 默认查询最新月份的数据
    @Override
    public List<CompanyData> selectAll() {
        LambdaQueryWrapper<CompanyData> companyDataLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 核心：默认查询最新月份的全部数据
        LocalDate latestMonth = getLatestMonth();
        if (latestMonth != null) {
            companyDataLambdaQueryWrapper.eq(CompanyData::getDataMonth, latestMonth);
        }
        companyDataLambdaQueryWrapper.orderByAsc(CompanyData::getId);
        List<CompanyData> list = companyDataMapper.selectList(companyDataLambdaQueryWrapper);
        return list;
    }

    @Override
    public Answer<Object> personResponsibleList() {
        List<CompanyData> companyData = companyDataMapper.selectList(new LambdaQueryWrapper<>());
        List<String> personResponsibleList = companyData.stream()
                .map(CompanyData::getPersonResponsible)
                .filter(Objects::nonNull)  // 过滤null值
                .flatMap(person -> {
                    // 按空格分割字符串，生成新的流
                    String[] parts = person.split(" ");
                    List<String> result = new ArrayList<>();
                    for (String part : parts) {
                        // 过滤掉分割后可能产生的空字符串
                        if (!part.trim().isEmpty()) {
                            result.add(part.trim());
                        }
                    }
                    return result.stream();
                })
                .distinct()  // 去重操作
                .collect(Collectors.toList());
        return Answer.ok(personResponsibleList);
    }

    @Override
    public Answer<Object> departmentName() {
        List<CompanyData> companyData = companyDataMapper.selectList(new LambdaQueryWrapper<>());
        List<String> departmentNameList = companyData.stream()
                .map(CompanyData::getDepartmentName)
                .filter(Objects::nonNull)  // 过滤null值
                .flatMap(person -> {
                    // 按空格分割字符串，生成新的流
                    String[] parts = person.split(" ");
                    List<String> result = new ArrayList<>();
                    for (String part : parts) {
                        // 过滤掉分割后可能产生的空字符串
                        if (!part.trim().isEmpty()) {
                            result.add(part.trim());
                        }
                    }
                    return result.stream();
                })
                .distinct()  // 去重操作
                .collect(Collectors.toList());
        return Answer.ok(departmentNameList);
    }

    @Override
    public Answer<Object> redCountDetails(JSONObject reqJson) {
        String name = reqJson.getString("name");
        LambdaQueryWrapper<CompanyData> companyDataLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LocalDate latestMonth = getLatestMonth();
        if (latestMonth != null) {
            companyDataLambdaQueryWrapper.ne(CompanyData::getDataMonth, latestMonth);
        } else {
            // 表中无数据，返回空列表
            return Answer.ok(Collections.emptyList());
        }
        companyDataLambdaQueryWrapper.eq(CompanyData::getName, name).eq(CompanyData::getLampStatus,2);
        List<CompanyData> companyDataList = companyDataMapper.selectList(companyDataLambdaQueryWrapper);
        List<String> stringList = new ArrayList<>();
        for (CompanyData companyData:companyDataList){
            stringList.add(companyData.getDataMonth().toString());
        }
        return Answer.ok(stringList);
    }

    @Override
    public Answer<Object> nameList() {
        List<CompanyData> companyData = companyDataMapper.selectList(new LambdaQueryWrapper<>());
        List<String> nameList = companyData.stream()
                .map(CompanyData::getName)
                .filter(Objects::nonNull)  // 过滤null值
                .flatMap(person -> {
                    // 按空格分割字符串，生成新的流
                    String[] parts = person.split(" ");
                    List<String> result = new ArrayList<>();
                    for (String part : parts) {
                        // 过滤掉分割后可能产生的空字符串
                        if (!part.trim().isEmpty()) {
                            result.add(part.trim());
                        }
                    }
                    return result.stream();
                })
                .distinct()  // 去重操作
                .collect(Collectors.toList());
        return Answer.ok(nameList);
    }
}
